const { JJUser, JJApply, JJApplyImages } = require('../../models/ctcdb');
const BaseResp = require('../../utils/baseResp');
const errorCode = require('../../utils/errorCode');
const _ = require('lodash');

/**
 * 教练申请提交
 * @param name
 * @param phone
 * @param description
 * @param images
 * @param userId
 * @param realName
 * @returns {Promise<*>}
 */
async function applyCommit({ name, phone, description, images, userId, realName }) {
  const userInfo = await JJUser.findOne({
    where: {
      id: userId
    },
    attributes: ['identity'],
    raw: true
  });
  const where = {
    JUserId: userId
  };
  let type = 0; // 增加
  let isNew = 1;
  if (userInfo.identity === 1) {
    type = 1; // 修改
    isNew = 0;
    where.status = 1 // 修改查询是否有正在审核的
  } else {
    where.isNew = 1; // 如果是新增，则查询最新的状态
  }
  // 一个人只能同时存在一个提交
  const applyInfo = await JJApply.findOne({
    where,
    raw: true
  });
  if (applyInfo && applyInfo.status === 1) {
    // 申请正在审核
    return Promise.reject(BaseResp.error(errorCode.USER.APPLY_IS_VERIFY))
  }
  // if (applyInfo && applyInfo.status === 10) {
  //   // 申请已通过
  //   return Promise.reject(BaseResp.error(errorCode.USER.APPLY_IS_ACCESS))
  // }
  // todo 考虑下是否加入事务
  try {
    // 创建申请表(images放到另一个表里面去,还是说用字符串数组标识，如果用字符串数组表示，就比较难修改)
    const { id: applyId } = await JJApply.create({
      name,
      phone,
      description,
      status: 1,
      JUserId: userId,
      isNew,
      realName,
      type
    });
    const array = [];
    images.forEach((item) => {
      array.push({
        imagePath: item.path,
        type: item.type,
        JApplyId: applyId,
        JUserId: userId
      })
    });
    await JJApplyImages.bulkCreate(array);
    if (applyInfo && applyInfo.status === -10) {
      // 修改最新的为false,如果是重新提交
      await JJApply.update({
        isNew: 0
      }, {
        where: {
          id: applyInfo.id
        }
      })
    }
  } catch (e) {
    return Promise.reject(e)
  }
}

/**
 * 获取当前教练的申请状态
 * @param userId
 * @returns {Promise<{status: number}>}
 */
async function getCommitStatus({ userId }) {
  const applyInfo = await JJApply.find({
    where: {
      isNew: 1,
      JUserId: userId,
      type: 0 // 获取增加的状态
    },
    attributes: ['id', 'status', 'refuseMark'],
    raw: true
  });
  const status = applyInfo ? applyInfo.status : 0;
  const refuseMark = applyInfo ? applyInfo.refuseMark : '';
  return {
    status,
    refuseMark
  };
}

async function getJiaoUserDetail({ userId }) {
  const applys = await JJApply.findAll({
    where: {
      isNew: 1,
      JUserId: userId,
      status: 10
      // type: 1
    },
    attributes: ['id', 'status', 'refuseMark', 'name', 'realName', 'description', 'refuseMark', 'type', 'isNew', 'phone'],
    raw: true
  });
  if (applys.length === 0) {
    throw BaseResp.error(errorCode.USER.NOT_JUSER_INFO)
  }
  let applyInfo = {};
  const applyMap = _.keyBy(applys, 'type');
  // 取最新修改的
  if (applyMap['1'] && applyMap['1'].isNew === 1 && applyMap['1'].status === 10) {
    applyInfo = applyMap['1']
  } else {
    applyInfo = applyMap['0']
  }
  const images = await JJApplyImages.findAll({
    where: {
      JApplyId: applyInfo.id,
      JUserId: userId
    },
    raw: true,
    attributes: ['imagePath', 'type']
  });
  applyInfo.images = images;
  return applyInfo
}

/**
 * 获取用户的基本信息
 * @param userId 用户Id
 * @param uid 用户Id
 * @returns {Promise<*>}
 */
async function getUserInfo({ userId, uid }) {
  const user = await JJUser.find({
    where: {
      id: userId
    },
    attributes: ['id', 'name', 'avatar', 'identity', 'description', 'phone'],
    raw: true
  });
  if (!user) {
    throw BaseResp.error(errorCode.USER.NOT_FOUND)
  }
  let images = [];
  let imagePath = '';
  if (uid) {
    const applys = await JJApply.findAll({
      where: {
        status: 10, // 查询审核通过的
        isNew: 1,
        JUserId: userId,
        // type: 1
      },
      attributes: ['id', 'status', 'refuseMark', 'name', 'realName', 'description', 'refuseMark', 'type', 'isNew'],
      raw: true
    });
    if (applys.length === 0) {
      throw BaseResp.error(errorCode.USER.NOT_JUSER_INFO)
    }
    let applyInfo = {};
    const applyMap = _.keyBy(applys, 'type');
    // 取最新修改的
    if (applyMap['1'] && applyMap['1'].isNew === 1 && applyMap['1'].status === 10) {
      applyInfo = applyMap['1']
    } else {
      applyInfo = applyMap['0']
    }
    if (applyInfo) {
      const { id } = applyInfo;
      images = await JJApplyImages.findAll({
        where: {
          type: 0,
          JApplyId: id
        },
        attributes: ['imagePath'],
        raw: true
      })
      // if (applyImageInfo) {
      //   imagePath = applyImageInfo.imagePath
      // }
    }
  }
  user.images = images;
  return user;
}

/**
 * 修改用户的基本信息
 * @param userId
 * @param name
 * @param avatar
 * @param phone
 * @returns {Promise<void>}
 */
async function modifyUserInfo({ userId, name, avatar, phone }) {
  const updateMap = {};
  if (name) {
    updateMap.name = name
  }
  if (avatar) {
    updateMap.avatar = avatar;
  }
  if (phone) {
    updateMap.phone = phone;
  }
  if (_.isEmpty(updateMap, true)) {
    throw BaseResp.error(errorCode.common.UPDATE_MUST_HAVE_ONE);
  }
  await JJUser.update(updateMap, { where: { id: userId } })
}

module.exports = {
  // 提交申请教练
  applyCommit,
  // 获取用户的提交状态
  getCommitStatus,
  // 获取教练详情的接口
  getJiaoUserDetail,
  // 获取用户的基本信息
  getUserInfo,
  // 修改用户基本信息
  modifyUserInfo
};
